<?php
/**
 * User: Woozee
 * Date: 2021/3/5
 * Time: 14:34
 */

namespace App\Console\Commands;

use App\Enum\Spider\SourceEnum;
use App\Libs\Helpers\Str;
use App\Libs\Vendor\Markdown\Markdown;
use App\Models\ArticlePool;
use App\Models\Spider\Pianshen;

class CleanSpiderArticle extends BaseCommand
{
    protected Markdown $markdown;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'spider:clean {--source=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '清洗爬虫数据';

    /**
     * 来源平台
     *
     * @var array
     */
    protected $sources = [];

    /**
     * Create a new command instance.
     *
     * @param Markdown $markdown
     */
    public function __construct(Markdown $markdown)
    {
        parent::__construct();
        $this->markdown = $markdown;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->initParams();
        in_array(SourceEnum::PIANSHEN, $this->sources) && $this->pianshen();
    }

    protected function pianshen()
    {
        $domain = config('global.pianshen_domain');
        Pianshen::chunk(1000, function ($data) use ($domain) {
            foreach ($data as $item) {
                /** @var \App\Models\Spider\Pianshen $item */
                if (empty($item->content)) {
                    continue;
                }
                $content = Str::addImgDomain($item->content, $domain);
                $poolItem = [
                    'title' => $item->title,
                    'content' => $this->markdown->toMarkdown($content),
                    'source' => SourceEnum::PIANSHEN,
                    'source_id' => $item->article_id,
                    'source_url' => $item->url,
                ];
                ArticlePool::updateOrCreate(['source' => $poolItem['source'], 'source_id' => $poolItem['source_id']], $poolItem);
            }
        });
    }

    protected function initParams(): void
    {
        if ($source = $this->option('source')) {
            $this->sources = explode(',', $source);
        } else {
            $this->sources = SourceEnum::getKeys();
        }
    }
}

